<?php

namespace Common\Model;
use Think\Model;

class MenuGoodsModel extends Model{


    protected $_validate = array(
        array( 'store_id', 'require', '商户必须选择' ),
        array( 'goods_id', 'require', '菜品必须选择' ),
        array( 'goods_storage', 'require', '库存必须填写' ),
    );
    
    protected $_auto = array(
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('update_time', NOW_TIME, self::MODEL_BOTH),
        array('status', '1', self::MODEL_INSERT),
    );


    /**
     * 新增或更新
     * 
     * @return boolean fasle 失败 ， int 成功 返回完整的数据
     */
    public function update($data)
    {
        $data = $this->create($data);
        if (empty($data)) {
            return false;
        }
        if (empty($data['id'])) {
            $id = $this->add();
            if (! $id) {
                $this->error = '新增出错';
                return false;
            }
        } else {
            $result = $this->where(array( 'id' => $data['id'] ))->save($data);
            if (false === $result) {
                $this->error = '更新出错';
                return false;
            }
        }
        
        return $data;
    }

    public function getMenuGoods($menuId, $goodsId = 0)
    {
        if (empty($menuId)){
            return false;
        }
        $join = 'INNER JOIN __GOODS__ AS g ON g.goods_id = m.goods_id';
        $field = 'm.menu_id,m.goods_id,m.goods_storage';
        $field .= ',g.goods_name,g.goods_thumb,g.cate_id,g.goods_combo,g.goods_image,g.market_price,g.shop_price,g.member_price,g.store_id';
        $where= array();
        $where['m.menu_id'] = $menuId;
        $where['m.status'] = 1;
        if ($goodsId){
            $where['m.goods_id'] = $goodsId;
        }
        $result = $this->table('__MENU_GOODS__ AS m')->join($join)->field($field)->where($where)->select();
        return $result;

    }

}
